package com.magicode.screen.wxapi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Window;
import android.widget.Toast;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppContext;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.bean.Constants;
import com.magicode.screen.thirdPart.wx.WxPayUtil;
import com.magicode.screen.util.UIHelper;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.Header;

import java.util.HashMap;
import java.util.Map;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

	private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

	private ReactInstanceManager mReactInstanceManager = null;
	private IWXAPI api;
	// private TextView reulttv;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//setContentView(R.layout.wx_pay_result);
		api = WXAPIFactory.createWXAPI(this, Constants.app_pay_weixin_appid);
		api.handleIntent(getIntent(), this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {

	}

	@Override
	public void onResp(BaseResp resp) {
	//	Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			builder.setTitle("支付中..");
//			builder.setMessage(getString(R.string.pay_result_callback_msg, String.valueOf(resp.errCode)));
//			builder.show();
			Intent intent;
			int code = resp.errCode;
			switch (code) {
				case 0:
					chechPayStatus(resp);
					//finish();
					break;
				case -1:
					Toast.makeText(this, "支付失败",Toast.LENGTH_SHORT).show();
//					chechPayStatus(resp);
					sendEventForReact(false);
					finish();
//					UIHelper.showPayFailReactActivity(getBaseContext());
//					finish();
					break;
				case -2:
					Toast.makeText(this, "支付取消",Toast.LENGTH_SHORT).show();
					finish();
					UIHelper.showPayFailReactActivity(getBaseContext());
					break;
				default:
					break;
			}
		}
	}
	public boolean chechPayStatus(BaseResp baseResp ){
		boolean result = false;
		if(baseResp instanceof  PayResp) {
			PayResp payResp = (PayResp) baseResp;
			String userToken =  AppContext.getInstance().getProperty("user.userToken");
			MgcApi.payCheck(WxPayUtil.outTradeId,userToken,checkPayHandler);
		}
		return result;
	}

	/**
	 * 验证支付状态
	 */
	private final AsyncHttpResponseHandler checkPayHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			try {
				AsyncHttpClient client = ApiHttpClient.getHttpClient();
//                HttpContext httpContext = client.getHttpContext();
				ObjectMapper mapper = new ObjectMapper();
				Map result = mapper.readValue(arg2, HashMap.class);
				Map entity = null;
				String payStatus = null;
				String status = null;
				String message = null;
				if(result != null){
					entity = (Map)result.get("entity");
					status = (String)result.get("status");
				}
				if(entity != null){
					payStatus = (String)entity.get("status");
//					message = (String)entity.get("message");
				}
				if("99".equals(status) && "success".equals(payStatus) ){
//					Toast.makeText(WXPayEntryActivity.this,payStatus, Toast.LENGTH_SHORT).show();
//					UIHelper.showPaySuccessReactActivity(getBaseContext());
					sendEventForReact(true);
					finish();
				}
				else{
					Toast.makeText(WXPayEntryActivity.this, "支付取消，请再次支付", Toast.LENGTH_SHORT).show();
//					UIHelper.showPayFailReactActivity(getBaseContext());
					sendEventForReact(false);
					finish();
				}
			} catch (Exception e) {
				e.printStackTrace();
				onFailure(arg0, arg1, arg2, e);
				sendEventForReact(false);
				finish();
			}
		}
		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							  Throwable arg3) {
//			AppContext.showToast("支付错误");
			sendEventForReact(false);
		}
	};

	private void sendEventForReact(Boolean result) {
		if(result != null) {
			ReactNativeHost rnh = AppContext.getInstance().getReactNativeHost();
			if (null != rnh) {
				mReactInstanceManager = rnh.getReactInstanceManager();
			}
			WritableMap params = Arguments.createMap();
			params.putString("status", result.toString());
			sendEvent(mReactInstanceManager.getCurrentReactContext(), "finishPay", params);
		}
	}
	private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
		reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
				.emit(eventName, params);
	}

	public void finish() {
		super.finish();
	}

	protected void onDestroy() {
		super.onDestroy();
	}
}